from rest_framework import generics
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework_simplejwt.views import TokenObtainPairView

from users.models import User
from users.serializers import UserRegisterSerializer, MyTokenObtainPairSerializer, UserSerializer
from utils.pagination import TenItemPerPagePagination


class UserRegisterView(generics.CreateAPIView):
    serializer_class = UserRegisterSerializer


class LoginView(TokenObtainPairView):
    """
    登录视图
    """
    serializer_class = MyTokenObtainPairSerializer


class UserViewSet(ModelViewSet):
    serializer_class = UserSerializer
    queryset = User.objects.all().order_by('-date_joined')  # 按创建时间倒序
    permission_classes = [IsAuthenticated]
    pagination_class = TenItemPerPagePagination

    @action(methods=['get'], detail=False)
    def menu(self, request, *args, **kwargs):
        data = {
            "code": 200,
            "data": {
                "menu": [
                ],
                "permissions": [
                    "list.add",
                    "list.edit",
                    "list.delete",
                    "user.add",
                    "user.edit",
                    "user.delete"
                ]
            },
            "message": ""
        }
        page0 = {
            "name": "home",
            "path": "/home",
            "meta": {
                "title": "首页",
                "icon": "el-icon-menu",
                "type": "menu"
            },
            "children": [
                {
                    "name": "dashboard",
                    "path": "/dashboard",
                    "meta": {
                        "title": "控制台",
                        "icon": "el-icon-menu",
                        "affix": True
                    },
                    "component": "home"
                },

            ]
        }  # 首页
        page2 = {
            "name": "manage",
            "path": "/manage",
            "meta": {
                "title": "管理",
                "icon": "el-icon-files",
                "type": "menu"
            },
            "children": [
            ]
        }

        page2_4 = {
            "path": "/manage/product",
            "name": "product",
            "meta": {
                "title": "产品信息",
                "icon": "el-icon-menu",
                "type": "menu"
            },
            "component": "manage/product"
        }  # 产品信息

        data['data']['menu'].append(page0)
        data['data']['menu'].append(page2)
        page2['children'].append(page2_4)

        return Response(data)
